package com.voja.mrvica2.adapter;

import java.util.ArrayList;

import com.voja.mrvica2.Entry;
import com.voja.mrvica2.R;
import com.voja.mrvica2.remoteimage.RemoteImageView;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EntryAdapter extends ArrayAdapter<Entry> {

    Context context;
    int     resourceId;
    public static ArrayList<Entry> entries;
    public static boolean loaded = false;
    public static boolean loading = false;
    
    public EntryAdapter(Context context, int resourceId, ArrayList<Entry> entries) {
        super(context, resourceId);
        
        this.context    	 = context;
        this.resourceId 	 = resourceId;
        EntryAdapter.entries = entries;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            v = inflater.inflate(resourceId, null);
        }
        
        Entry entry = entries.get(position);
        if (entry != null) {
            RemoteImageView image = (RemoteImageView)v.findViewById(R.id.itemImage);
            TextView        title = (TextView)v.findViewById(R.id.itemTitle);
            LinearLayout    throb = (LinearLayout)v.findViewById(R.id.throbber);
            
            if (entry.getId() > 0) {
                throb.setVisibility(View.GONE);
                image.setVisibility(View.VISIBLE);
                title.setVisibility(View.VISIBLE);
                
                title.setText(entry.getTitle());
                image.setImage(entry.getImage());
            } else {
                
                
                throb.setVisibility(View.VISIBLE);
                image.setVisibility(View.GONE);
                title.setVisibility(View.GONE);
            }
        }
        
        return v;
    }
    
    @Override
    public void add(Entry entry) {
        entries.add(entry);
        super.add(entry);
    }
    
    public void remove(int position, Entry entry) {
        entries.remove(position);
        super.remove(entry);
    }
    
    @Override
    public Entry getItem(int position) {
        return entries.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        Entry item = getItem(position);
        return item.getId();
    }
    
    @Override
    public int getCount() {
        int size = 0;
        if (entries != null) {
            size = entries.size();
        }
        return size;
    }
    
    public void removeLast() {
        int   position  = getCount() - 1;
        Entry entry     = getItem(getCount() - 1);
        remove(position, entry);
    }
}
